package api

import (
	"context"
	"github.com/gin-gonic/gin"
	"goFunc/forms"
	"goFunc/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
	"net/http"
)

func Login(ctx *gin.Context) {
	//用户注册
	//Query 只支持get请求
	//PostForm 都支持
	userName := ctx.PostForm("userName")

	ctx.JSON(200, gin.H{
		"data": userName,
		"code": "success",
	})
}

func Register(ctx *gin.Context) {
	var u forms.RegisterVilidate
	if err := ctx.ShouldBindJSON(&u); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{
			"msg": err.Error(),
		})
		return
	}
	//连接grpc 并且调用接口
	conn, err := grpc.NewClient("localhost:50001", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()
	client := proto.NewUserClient(conn)

	// Contact the server and print out its response.
	//context, cancel := context.WithTimeout(context.Background(), time.Second)
	//defer cancel()
	r, err := client.Register(context.Background(), &proto.RegisterRequest{Username: u.UserName, Password: u.Password, Mobile: u.Mobile})
	if err != nil {
		log.Fatalf("could not greet: %v", err)
	}
	ctx.JSON(200, gin.H{
		"data": r.Username,
		"code": "success",
	})
}
